package com.fary.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.io.IOException;
import java.util.*;

public class MyBeanSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        // 循环所有的beanPropertyWriter
        for (BeanPropertyWriter beanProperty : beanProperties) {
            SerializableString serializedName = beanProperty.getSerializedName();
            JavaType type = beanProperty.getType();
            JsonInclude annotation = beanProperty.getAnnotation(JsonInclude.class);
            if (isArrayType(beanProperty)) {
                beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                    @Override
                    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                        System.out.println();
                        if (value == null) {
                            gen.writeStartArray();
                            gen.writeEndArray();
                        }
                    }
                });
            } else if (isStringType(beanProperty)) {
                beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                    @Override
                    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                        System.out.println();
                        gen.writeString("");
                    }
                });
            }
        }
        return beanProperties;
    }

    private boolean isArrayType(BeanPropertyWriter beanProperty) {
        Class<?> rawClass = beanProperty.getType().getRawClass();
        return rawClass.isArray() || Collection.class.isAssignableFrom(rawClass);
    }

    private boolean isStringType(BeanPropertyWriter beanProperty) {
        Class<?> rawClass = beanProperty.getType().getRawClass();
        return CharSequence.class.isAssignableFrom(rawClass) || Character.class.isAssignableFrom(rawClass);
    }

}
